#pragma once

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>



#include "Log.hpp"

const int Back_log = 5;

Log lg;

enum{
    SOCK_ERR = 1,
    BIND_ERR,
    LISTEN_ERR,
    ACCETP_ERR,
};

class Socket
{
public:
    Socket()
    {}

    void Getsocket()
    {
        _socketfd = socket(AF_INET,SOCK_STREAM,0);
        if(_socketfd<0)
        {
            lg(Fatal,"socket is error %d",strerror(errno));
            exit(SOCK_ERR);
        } 
    }

    void Getbind(uint16_t port)
    {
        struct sockaddr_in _obj;
        bzero(&_obj,sizeof(_obj));

        _obj.sin_family = AF_INET;
        _obj.sin_port = htons(port);
        _obj.sin_addr.s_addr = INADDR_ANY;

        socklen_t len = sizeof(_obj);
        int ret = bind(_socketfd,(struct sockaddr*)&_obj,len);
        //if(ret == -1)
        if(ret <0)
        {
             lg(Fatal,"bind is error %d",strerror(errno));
            //lg(Fatal,"bind is error %s",(errno));

            exit(BIND_ERR);
        }
    }

    void Getlisten()
    {
        int ret = listen(_socketfd,Back_log);
        if(ret<0)
        {
            lg(Fatal,"listen is error %d",strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    int Getaccept(std::string *outip,uint16_t *port)
    {
        struct sockaddr_in _client;
        bzero(&_client,sizeof(_client));
        socklen_t len = sizeof(_client);

        int ret = accept(_socketfd,(struct sockaddr*)&_client,&len);
        if(ret<0)
        {
            lg(Fatal,"accept is error %d",strerror(errno));
            exit(ACCETP_ERR);
        }
        *port = ntohs(_client.sin_port);
        //const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);

        char buffer[64];
        inet_ntop(AF_INET,&_client,buffer,sizeof(buffer));
        *outip = buffer;

        return ret;
    }
    //int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
    bool Getconnect(std::string &ip,uint16_t &port)
    {
        struct sockaddr_in Server;
        Server.sin_family=AF_INET;
        Server.sin_port=htons(port);
        inet_aton(ip.c_str(),&Server.sin_addr);

        socklen_t len = sizeof(Server);
        int ret = connect(_socketfd,(struct sockaddr*)&Server,len);
        if(ret<0)
        {
            lg(Fatal,"connect is error %d",strerror(errno));
            return false;
        }
        return true;
    }

    int Ret_fd()
    {
        return _socketfd;
    }

    void Close()
    {
        close(_socketfd);
    }

    ~Socket()
    {}
private:
int _socketfd;
};



